var myApp = angular.module('myApp', [ 'ngGrid', 'ui.select2' ]);
myApp.controller('orderHeadCtrl', function($scope, $http, $filter) {
	//global variable
	$scope.selectedRows = [];
	//init page item
	$scope.init = function() {
		$('input[name="orderDt"], input[name="billingDt"], input[name="planlDt"], input[name="planaDt"]').datetimepicker({
			minView: "month",
			format: "yyyy-mm-dd hh:ii",
		    todayBtn: "linked",
		    language: "zh-CN",
		    forceParse: false,
		    autoclose: true,
		    todayHighlight: true
		});
		$('input[name="orderDt1"], input[name="orderDt2"],input[name="planaDt1"], input[name="planaDt2"]').datetimepicker({
			minView: "month",
			format: "yyyy-mm-dd",
			todayBtn: "linked",
			language: "zh-CN",
			forceParse: false,
			autoclose: true,
			todayHighlight: true
		});
		$scope.stList = [{"id":0, "lb":"在用"},{"id":1, "lb":"停用"}];
		httpPost($http, {"url":ctx+"/client/findListByFirst", "data": {"ffMap":{"st":0}}}, function(data){
			$scope.clientList = data.dt;
		}, function(){
			toastError("初始化客户列表失败。");
		});
		httpPost($http, {"url":ctx+"/dict/findListBy", "data": {"ffMap":{"cd":"vocation","st":0}}}, function(data){
			$scope.cdList = data.dt;	
		}, function(){
			toastError("初始化业务类型列表失败。");
		});
		httpPost($http, {"url":ctx+"/dict/findListBy", "data": {"ffMap":{"cd":"shipmentMethod","st":0}}}, function(data){
			$scope.shipment_methodList = data.dt;	
		}, function(){
			toastError("初始化运输方式列表失败。");
		});
		httpPost($http, {"url":ctx+"/dict/findListBy", "data": {"ffMap":{"cd":"status","st":0}}}, function(data){
			$scope.statusList = data.dt;	
		}, function(){
			toastError("初始化状态列表失败。");
		});
		httpPost($http, {"url":ctx+"/transLocation/findListByFirst", "data": {"ffMap":{"st":0}}}, function(data){
			$scope.translocationList = data.dt;
		}, function(){
			toastError("初始化运输地列表失败。");
		});
	};
	$scope.init();
	//grid订单管理
	$scope.pagingOptions = {
		pageSizes : [ 20, 50, 100 ],
		pageSize : 20,
		currentPage : 1,
		onQueryFlag : false
	};
	
	$scope.$watch('pagingOptions', function(newVal, oldVal) {
		if (newVal !== oldVal/* && newVal.currentPage !== oldVal.currentPage*/) {
			$scope.query();
		}
	}, true);
	$scope.gridOptions = {
		data : 'dt',
		totalServerItems : 'tt',
		
		columnDefs : [
		{
			field : "id",
			displayName : "ID", visible : false
		},
		{
			field : "clientName",
			displayName : "所属客户", width : 200
		},
		{
			field : "cd",
			displayName : "订单号", width : 160
		},
		{
			field : "shipmentMethodName",
			displayName : "运输方式", width : 120
		},
		{
			field : "vocationName",
			displayName : "业务类型", width : 120
		},
		{
			field : "statusName",
			displayName : "状态", width : 120
		},
		{
			field : "typeName",
			displayName : "订单类型", width : 120
		},
		{
			field : "orderDt",
			displayName : "开单时间", width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "planlDt",
			displayName : "计划出发时间", width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "planaDt",
			displayName : "计划到达时间", width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "billingDt",
			displayName : "计费周期", width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "quantity",
			displayName : "数量", width : 120,
		},
		{
			field : "weight",
			displayName : "重量", width : 120
		},
		{
			field : "volume",
			displayName : "体积", width : 120
		},
		{
			field : "palletsum",
			displayName : "托数", width : 120
		},
		{
			field : "expense",
			displayName : "一口价", width : 120
		},
		{
			field : "freceiverCd",
			displayName : "发货方代码", width : 120
		},
		{
			field : "freceiverName",
			displayName : "发货方名称", width : 120
		},
		{
			field : "ftranslocationName",
			displayName : "出发地", width : 120
		},
		{
			field : "freceiverLikename",
			displayName : "发货方联系人", width : 120
		},
		{
			field : "freceiverPhone",
			displayName : "发货方联系电话", width : 120
		},
		{
			field : "freceiverFax",
			displayName : "发货方传真", width : 120
		},
		{
			field : "freceiverEmail",
			displayName : "发货方邮箱", width : 120
		},
		{
			field : "freceiverPostcode",
			displayName : "发货方邮编", width : 120
		},
		{
			field : "freceiverAddress",
			displayName : "发货方地址", width : 200
		},
		{
			field : "treceiverCd",
			displayName : "收货方代码", width : 120
		},
		{
			field : "treceiverName",
			displayName : "收货方名称", width : 250
		},
		{
			field : "ttranslocationName",
			displayName : "目的地", width : 120
		},
		{
			field : "treceiverLikename",
			displayName : "收货方联系人", width : 120
		},
		{
			field : "treceiverPhone",
			displayName : "收货方联系电话", width : 120
		},
		{
			field : "treceiverFax",
			displayName : "收货方传真", width : 120
		},
		{
			field : "treceiverEmail",
			displayName : "收货方邮箱", width : 120
		},
		{
			field : "treceiverPostcode",
			displayName : "收货方邮编", width : 120
		},
		{
			field : "treceiverAddress",
			displayName : "收货方地址", width : 250
		},
		{
			field : "descr",
			displayName : "描述", width : 120
		}
		],
		enablePaging : true,
		pagingOptions : $scope.pagingOptions,
		enableCellEdit:true,
		//enableCellSelection:true,
		//enablePinning : true,
		//showColumnMenu : true,
		//showGroupPanel : true,
		showSelectionCheckbox : true,
		selectedItems : $scope.selectedRows,
		i18n: 'zh-cn', rowHeight : 20.2, footerRowHeight : 35, //plugins : [/*new ngGridFlexibleHeightPlugin()*/ ],
		//rowTemplate : '<div ng-click="select()" ng-style="{ \'cursor\': row.cursor }" ng-repeat="col in renderedColumns" ng-class="col.colIndex()" class="ngCell {{col.cellClass}}"><div class="ngVerticalBar" ng-style="{height: rowHeight}" ng-class="{ ngVerticalBarVisible: !$last }">&nbsp;</div><div ng-cell></div></div>',
		showFooter : true,
		afterSelectionChange : function(rowItem, event){
			var sts =[];
			for(var i=0;i<$scope.selectedRows.length;i++){
				var st = $scope.selectedRows[i]['status'];
				if(jQuery.inArray( st, sts ) < 0){
					sts.push(st);
				}
			}
					
			//錄入中
			if(sts.length == 1 && sts[0] == 'INPUT'){
				$scope.flagOfConfirmOrderBtn = false;
			}else{
				$scope.flagOfConfirmOrderBtn = true;
			}
			//生效
			if(sts.length == 1 && sts[0] == 'SIGNED'){
				$scope.flagOfEnableOrderBtn = false;
			}else{
				$scope.flagOfEnableOrderBtn = true;
			}
			//失效
			if(sts.length == 1 && sts[0] == 'ARRIVED'){
				$scope.flagOfDisableOrderBtn = false;
			}else{
				$scope.flagOfDisableOrderBtn = true;
			}
		}
	};
	
	
	$scope.query = function() {
		closeModal($("#queryFormModal"));
		var requestBody = {
			pageNb : $scope.pagingOptions.currentPage,
			pageSize : $scope.pagingOptions.pageSize,
			ffMap : $scope.queryForm
		};
		setTimeout(function() {
			httpPost($http, {"url":ctx + '/orderHead/findListBy', "data":requestBody, "ifBlock":false}, function(data){	
				$scope.tt = data.tt;
				$scope.dt = data.dt;
				$scope.gridOptions.$gridScope.toggleSelectAll(false);
			}, function(errMsg){
				toastError("查询失败。" + errMsg);
			});
		}, 100);
	};
	//trigger query when currentPage not change
	$scope.onQuery = function(){
		console.log( $scope.queryForm);
		$scope.pagingOptions.onQueryFlag = !$scope.pagingOptions.onQueryFlag;
		$scope.pagingOptions.currentPage = 1;
	};

	//订单明细
	$scope.pagingOption = {
			pageSizes : [ 20, 50, 100 ],
			pageSize : 20,
			currentPage : 1,
			onQueryFlag : false
		};
		
		$scope.$watch('pagingOption', function(newVal, oldVal) {
			if (newVal !== oldVal/* && newVal.currentPage !== oldVal.currentPage*/) {
				$scope.query1();
			}
		}, true);
		$scope.gridOption = {
			data : 'd',
			totalServerItems : 't',
			
			columnDefs : [
			{
				field : "id",
				displayName : "ID", visible : false
			},
			{
				field : "lineno",
				displayName : "行号",width:160
			},
			{
				field : "productName",
				displayName : "货物名称",width:160
			},
			{
				field : "lot",
				displayName : "批号",width:160
			},
			{
				field : "statusName",
				displayName : "审核结果",width:160
			},
			{
				field : "unit",
				displayName : "包装",width:160
			},
			{
				field : "quantity",
				displayName : "数量",width:160
			},
			{
				field : "weight",
				displayName : "重量",width:160
			},
			{
				field : "volume",
				displayName : "体积",width:160
			}
			],
			enablePaging : true,
			pagingOptions : $scope.pagingOption,
			enableCellEdit:true,
			//enablePinning : true,
			//showColumnMenu : true,
			//showGroupPanel : true,
			showSelectionCheckbox : true,
			selectedItems : $scope.selectedRow,
			i18n: 'zh-cn', rowHeight : 23, footerRowHeight : 35, //plugins : [/*new ngGridFlexibleHeightPlugin()*/ ],
			//rowTemplate : '<div ng-click="select()" ng-style="{ \'cursor\': row.cursor }" ng-repeat="col in renderedColumns" ng-class="col.colIndex()" class="ngCell {{col.cellClass}}"><div class="ngVerticalBar" ng-style="{height: rowHeight}" ng-class="{ ngVerticalBarVisible: !$last }">&nbsp;</div><div ng-cell></div></div>',
			showFooter : true
		};
		
		
		$scope.query1 = function() {
			var requestBody = {
				pageNb : $scope.pagingOption.currentPage,
				pageSize : $scope.pagingOption.pageSize,
				ffMap : $scope.queryForm1
			};
			setTimeout(function() {
				httpPost($http, {"url":ctx + '/orderDetail/findListBy', "data":requestBody, "ifBlock":false}, function(data){
					$scope.t = data.tt;
					$scope.d = data.dt;
					$scope.gridOption.$gridScope.toggleSelectAll(false);
				}, function(errMsg){
					toastError("查询失败。" + errMsg);
				});
			}, 100);
		};
		//trigger query when currentPage not change
	$scope.refresh=function(){
		$scope.onQuery();
	};

	//utils
	$scope.onClearSelectedRows = function() {
		$scope.gridOptions.$gridScope.toggleSelectAll(false);
	};
	//导入
	$scope.onOpenImportFormModal = function(){
		$scope.importForm={};
		$scope.importForm.importUrl="/orderHead/import";
		$("input[name='file']").css("width","200px").css("height","30px").css("padding-bottom","2px");
		openModal($("#importFormModal"));
	};
	
	$scope.onImport = function(){
		closeModal($("#importFormModal"));
		$("form[name='importFormForm']").submit();
	};
	//下载模板
	$scope.onExportTemplate = function(){
		if(isNull($scope.importForm) || isNull($scope.importForm.importUrl)){
			toastWarning("请选择导入项，以下载相应模板。");
			return;
		}
		window.open(ctx + $scope.importForm.importUrl + '/template');
	};
	//导出
	$scope.onOpenExportFormModal=function(){
		var params = $scope.queryForm;
		var str = jQuery.param(params);
		window.open(ctx  + '/orderHead/export?'+str);
	};
	//crud
	$scope.onOpenQueryFormModal = function() {
		httpPost($http, {"url":ctx+"/orderType/findListBy", "data": {"ffMap":{"st":0}}}, function(data){
			$scope.orderTypeList = data.dt;	
		}, function(){
			toastError("初始化状态列表失败。");
		});
		var date= (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) +"-"+((date.getDate() > 9) ? date.getDate() : "0" + date.getDate());
		if($scope.queryForm.planaDt1==undefined){
			$scope.queryForm.planaDt1=now;
		};
		if($scope.queryForm.planaDt2==undefined){
			$scope.queryForm.planaDt2=now;
		};
		openModal($("#queryFormModal"));
	};
	$scope.onOpenEditFormModal = function(type, id,cd) {
		$scope.disabledSubmitBtnOfEditForm=false;
		if(type=="add"){
			$scope.editForm = {};
			$scope.flagOfClientCd=false;
			$scope.flagOfCd=false;
			$scope.editForm.quantity=0;
			$scope.editForm.weight=0;
			$scope.editForm.volume=0;
			$scope.editForm.palletsum=0;
			$scope.editForm.expense=0;
			//根据客户获取它下面的订单类型
			$("#e").change(function(){
				var id=$(this).attr("value");
				httpPost($http, {"url":ctx+"/orderType/findListBy", "data": {"ffMap":{"clientId":id}}}, function(data){
						$scope.orderTypeList = data.dt;
					}, function(){
						toastError("初始化订单类型列表失败。");
					});
				httpPost($http, {"url":ctx+"/receiver/findListBy", "data": {"ffMap":{"clientId":id}}}, function(data){
					$scope.receiverList = data.dt;
				}, function(){
					toastError("初始化收发货方列表失败。");
				});
			});
			//带出运输方式
			$("#ot").click(function(){
				var id=$scope.editForm.orderTypeId;
				httpGet($http, {"url":ctx+'/orderType/id/'+id, "ifBlock":true}, function(data){
						$scope.editForm.shipment_method=data.dt['shipment_method'];
				});					
			});
			//收发货方
			$("#f").click(function(){	
					var id=$scope.editForm.freceiverId;
					httpGet($http, {"url":ctx+'/receiver/id/'+id, "ifBlock":true}, function(data){					
							$scope.editForm.freceiverName=data.dt["name"];
							$scope.editForm.ftranslocationId=data.dt["translocationId"];
							$scope.editForm.freceiverLikename=data.dt["likeman"];
							$scope.editForm.freceiverPhone=data.dt["phone"];
							$scope.editForm.freceiverFax=data.dt["fax"];
							$scope.editForm.freceiverEmail=data.dt["email"];
							$scope.editForm.freceiverPostcode=data.dt["postcode"];
							$scope.editForm.freceiverAddress=data.dt["address"];				
					}, function(){
						toastError("初始化收发货方类型列表1失败。");
				});			
			});
			$("#s").click(function(){
					var id=$scope.editForm.treceiverId;
					httpGet($http, {"url":ctx+'/receiver/id/'+id, "ifBlock":true}, function(data){					
							$scope.editForm.treceiverName=data.dt["name"];
							$scope.editForm.ttranslocationId=data.dt["translocationId"];
							$scope.editForm.treceiverLikename=data.dt["likeman"];
							$scope.editForm.treceiverPhone=data.dt["phone"];
							$scope.editForm.treceiverFax=data.dt["fax"];
							$scope.editForm.treceiverEmail=data.dt["email"];
							$scope.editForm.treceiverPostcode=data.dt["postcode"];
							$scope.editForm.treceiverAddress=data.dt["address"];				
					}, function(){
						toastError("初始化收发货方类型列表失败。");
				});
			});
			ids={"orderId":0};
			$scope.onQuery1 = function(){
				$scope.pagingOption.onQueryFlag = !$scope.pagingOption.onQueryFlag;
				$scope.pagingOption.currentPage = 1;
				$scope.queryForm1=ids;
			};	
			$scope.onQuery1();
		}else if(type=="upd"){
			if($scope.selectedRows.length != 1) { toastWarning("请选择一笔记录进行编辑。"); return; }
			$scope.flagOfClientCd=true;
			$scope.flagOfCd=true;
			httpGet($http, {"url":ctx+'/orderHead/id/'+$scope.selectedRows[0]['id'], "ifBlock":true}, function(data){
				$scope.editForm = data.dt;
				
				if($scope.selectedRows[0]['status']=='ARRIVED'){
					$scope.disabledSubmitBtnOfEditForm = true;
				}
				//将实体bean中的date类型format成字符串
				if($scope.editForm.orderDt!=null){
					$scope.editForm.orderDt = date2Ymdhms(data.dt.orderDt);
				}
				if($scope.editForm.billingDt!=null){
					$scope.editForm.billingDt = date2Ymdhms(data.dt.billingDt);
				}
				if($scope.editForm.planlDt!=null){
					$scope.editForm.planlDt = date2Ymdhms(data.dt.planlDt);
				}
				if($scope.editForm.planaDt!=null){
					$scope.editForm.planaDt = date2Ymdhms(data.dt.planaDt);
				}
				
				var clientId=data.dt['clientId'];
				httpPost($http, {"url":ctx+"/orderType/findListBy", "data": {"ffMap":{"clientId":clientId}}}, function(data){
					$scope.orderTypeList = data.dt;
				}, function(){
					toastError("初始化订单类型列表失败。");
				});
				httpPost($http, {"url":ctx+"/receiver/findListBy", "data": {"ffMap":{"clientId":clientId}}}, function(data){
					$scope.receiverList = data.dt;
				}, function(){
					toastError("初始化收发货方列表失败。");
				});
				//带出运输方式
				$("#ot").click(function(){
					var id=$scope.editForm.orderTypeId;
					httpGet($http, {"url":ctx+'/orderType/id/'+id, "ifBlock":true}, function(data){
							$scope.editForm.shipment_method=data.dt['shipment_method'];
					});					
				});
				//收发货方
				$("#f").click(function(){	
						var id=$scope.editForm.freceiverId;
						httpGet($http, {"url":ctx+'/receiver/id/'+id, "ifBlock":true}, function(data){					
								$scope.editForm.freceiverName=data.dt["name"];
								$scope.editForm.ftranslocationId=data.dt["translocationId"];
								$scope.editForm.freceiverLikename=data.dt["likeman"];
								$scope.editForm.freceiverPhone=data.dt["phone"];
								$scope.editForm.freceiverFax=data.dt["fax"];
								$scope.editForm.freceiverEmail=data.dt["email"];
								$scope.editForm.freceiverPostcode=data.dt["postcode"];
								$scope.editForm.freceiverAddress=data.dt["address"];				
						}, function(){
							toastError("初始化收发货方列表失败。");
					});			
				});
				$("#s").click(function(){
						var id=$scope.editForm.treceiverId;
						httpGet($http, {"url":ctx+'/receiver/id/'+id, "ifBlock":true}, function(data){					
								$scope.editForm.treceiverName=data.dt["name"];
								$scope.editForm.ttranslocationId=data.dt["translocationId"];
								$scope.editForm.treceiverLikename=data.dt["likeman"];
								$scope.editForm.treceiverPhone=data.dt["phone"];
								$scope.editForm.treceiverFax=data.dt["fax"];
								$scope.editForm.treceiverEmail=data.dt["email"];
								$scope.editForm.treceiverPostcode=data.dt["postcode"];
								$scope.editForm.treceiverAddress=data.dt["address"];				
						}, function(){
							toastError("初始化收发货方列表失败。");
					});
				});
			}, function(errMsg){
				toastWarning("查询此笔记录失败。");
			});
			var id=$scope.selectedRows[0]['id'];
			ids={"orderId":id};
			$scope.onQuery1 = function(){
				$scope.pagingOption.onQueryFlag = !$scope.pagingOption.onQueryFlag;
				$scope.pagingOption.currentPage = 1;
				$scope.queryForm1=ids;
			};	
			$scope.onQuery1();
			}
		openModal($("#editFormModal"));	
		$("#editFormModal .modal-body").css("padding","3px");
		$(".modal-body").css("overflow","hidden");
		$("#mainData .ngViewport").height(100);
		};
	$scope.onSaveEditForm = function(){
		closeModal($("#editFormModal"));
		//转回date类型以匹配实体bean中的类型
		if($scope.editForm.orderDt!=undefined){
			$scope.editForm.orderDt = ymdhms2date($scope.editForm.orderDt);
		}else{
			$scope.editForm.orderDt=null;
		}
		if($scope.editForm.billingDt!=undefined){
			$scope.editForm.billingDt = ymdhms2date($scope.editForm.billingDt);		
		}else{
			$scope.editForm.billingDt=null;
		}
		if($scope.editForm.planlDt!=undefined){
			$scope.editForm.planlDt = ymdhms2date($scope.editForm.planlDt);
		}else{
			$scope.editForm.planlDt=null;
		}
		if($scope.editForm.planaDt!=undefined){
			$scope.editForm.planaDt = ymdhms2date($scope.editForm.planaDt);
		}else{
			$scope.editForm.planaDt=null;
		}			
		httpPost($http, {"url":ctx + '/orderHead/save', "data":$scope.editForm, "ifBlock":true}, function(data){
			toastSuccess("保存成功");
			$scope.query();
		}, function(errMsg){
			toastError("保存失败,您输入的信息有误，请检查正确之后再保存。" + errMsg);
		});
	};
	
	
	$scope.onChangeSt = function(st, lb){
		var selectedRowsId = [];
			$.each($scope.selectedRows, function(idx, obj){
				selectedRowsId.push(obj.id);
			});
		if(st=="INPUT"){
			var ids=[];
			var tempShipmentIds=[];
			var orderCd=[];
			var object=[];
			httpPost($http, {"url":ctx + '/legs/findByIds', "params":{"ids":selectedRowsId}, "ifBlock":true}, function(data){
				for(var i=0;i<data.dt.length;i++){
					if(data.dt[i]['st']!='shipment'){
						orderCd.push(data.dt[i]['orderCd']);
					}else{
						for(var j=0;j<selectedRowsId.length;j++){
							if($scope.selectedRows[j]['id']==data.dt[i]['orderId']){
								object.push(data.dt[i]);
							}
						}
						ids.push(data.dt[i]['orderId']);
						tempShipmentIds.push(data.dt[i]['tempshipmentId']);
					}
				}
				httpPost($http, {"url":ctx + '/orderHead/updStByIds',"params":{"ids":ids, "status":st}, "ifBlock":true}, function(data){
					toastSuccess("共"+$scope.selectedRows.length+"个订单，"+ids.length+"个订单"+lb+"成功");
					httpPost($http, {"url":ctx + '/orderHead/back',"data":object,"params":{"ids":ids,"tempShipmentIds":tempShipmentIds}, "ifBlock":true}, function(data){
						
					});
					if(orderCd.length>0){
						alert("订单"+orderCd.toString()+lb+"失败,该订单已经被配载。");
					}
				}, function(errMsg){
					alert("订单"+orderCd.toString()+lb+"失败,该订单已经被配载。");
				});
			});
			$scope.onQuery();
		}else{
			httpPost($http, {"url":ctx + '/orderHead/updStByIds', "params":{"ids":selectedRowsId, "status":st}, "ifBlock":true}, function(data){
				toastSuccess("共"+$scope.selectedRows.length+"个订单"+lb+"成功");
			if(st=='ARRIVED'){
				var vocations =[];
				var object=[];
				for(var i=0;i<$scope.selectedRows.length;i++){
					object.push($scope.selectedRows[i]);
					var vocation = $scope.selectedRows[i]['vocation'];
					if(jQuery.inArray( vocation, vocations ) < 0){
						vocations.push(vocation);
					}
				}
				httpPost($http, {"url":ctx + '/orderHead/arrived',"data":object,"params":{"ids":selectedRowsId,"code":"未配载","vocations":vocations}, "ifBlock":true}, function(data){
					
				});
				};
				$scope.onQuery();
			}, function(errMsg){
				toastError("共"+$scope.selectedRows.length+"个订单"+lb+"失败" + errMsg);
			});
		};
	};
});
